package cn.lg.soar.boot.fc.service.impl;

import cn.lg.soar.boot.fc.constants.RentConstant;
import cn.lg.soar.boot.fc.entity.vo.FcTreeVo;
import cn.lg.soar.boot.fc.tool.RentValidation;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.ParameterUtil;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.boot.fc.mapper.RentMapper;
import cn.lg.soar.boot.fc.entity.Rent;
import cn.lg.soar.boot.fc.service.RentService;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.*;

/**
 * 租金管理表
 * @author BoBo
 * @since 2025-02-06
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class RentServiceImpl extends BaseServiceImpl<RentMapper, Rent> implements RentService {


    @Override
    public HttpResult<Serializable> addRent(Rent rent) {
        //租金名称不能为空
        if (rent.getName()==null || rent.getName().isEmpty()) {
            return HttpResult.fail("B0000", I18n.build("租金名称不能为空！"));
        }

        //租金核算方式不能为空
        if (rent.getRentaccounting()==null) {
            return HttpResult.fail("B0000", I18n.build("租金核算方式不能为空！"));
        }
        //租金核算方式为免租时，租金金额默认为0
        if (rent.getRentaccounting() == RentConstant.ACCOUNTING_RENT_FREE) {
            //租金金额为0
            rent.setRentamount("0");
        }
        //租金核算方式不是免租时，租金金额不能为空
        if (rent.getRentaccounting() == RentConstant.ACCOUNTING_FIXED
                || rent.getRentaccounting()==RentConstant.ACCOUNTING_AREA_COUNT) {
            if (rent.getRentamount()==null || rent.getRentamount().isEmpty() || rent.getRentamount().equals("0")) {
                return HttpResult.fail("B0000", I18n.build("租金金额不能为空或0！"));
            }
        }
        //当租金涨幅类型不为空时 判断是阶梯还是什么
        if (rent.getIncreasetype()!=null) {
            //当租金涨幅类型为阶梯租金时，涨幅阶梯大字段不能为空
            if (rent.getIncreasetype()==RentConstant.INCREASE_TYPE_STAIRS) {
                List<Map<String, Object>> ladderList = rent.getLadderList();
                //[{"index":1,"floatType":"1","changeValueOption":"1","changeTime":"23","changeValue":"3232"}]
                for (int i = 0; i < ladderList.size(); i++) {
                    Map<String, Object> map = ladderList.get(i);
                    //判断涨租时间
                    if (map.get("changeTime").toString()==null || map.get("changeTime").toString().isEmpty()) {
                        //返回阶梯几的浮动类型为空
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租时间不能为空！"));
                    }
                    //校验涨租时间的数据类型
                    if (!RentValidation.containsOnlyDigits(map.get("changeTime").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租时间只能是正整数,且在1-600之间！"));
                    }
                    //判断浮动类型
                    if (map.get("floatType").toString()== null || map.get("floatType").toString().isEmpty()) {
                        //返回阶梯几的浮动类型为空
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的浮动类型不能为空！"));
                    }
                    if (!RentValidation.isFloatType(map.get("floatType").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的浮动类型只能是上浮或下浮！"));
                    }
                    //涨租金额类型
                    if (map.get("changeValueOption").toString()==null || map.get("changeValueOption").toString().isEmpty()) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额类型不能为空！"));
                    }
                    if (!RentValidation.isFloatType(map.get("changeValueOption").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额类型只能是%或金额！"));
                    }

                    //涨租金额
                    if (map.get("changeValue").toString()==null || map.get("changeValue").toString().isEmpty()) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额不能为空！"));
                    }
                    //校验涨租金额
                    if (!RentValidation.isWithinRange(map.get("changeValue").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额只能输入1-10000000之间的数字！"));
                    }
                }
                //将涨幅阶梯数据转为String类型存入涨幅阶梯中
                String toJSONString = JSONArray.toJSONString(rent.getLadderList());

                rent.setIncreasecontent(toJSONString);
                if (rent.getIncreasecontent()==null || rent.getIncreasecontent().isEmpty()) {
                    return HttpResult.fail("B0000", I18n.build("涨幅阶梯不能为空！"));
                }
            }
            //如果是定额租金，将阶梯置为空
            if (rent.getIncreasetype()==RentConstant.INCREASE_TYPE_QUOTA) {
                rent.setIncreasecontent("");
            }
        }

        ParameterUtil.notNull(rent, "数据不能为空");
        AssertUtil.isTrue(super.save(rent), "创建失败");
        return HttpResult.success("创建成功");
    }

    @Override
    public HttpResult<Serializable> updateRent(Rent rent) {
        //租金名称不能为空
        if (rent.getName()==null || rent.getName().isEmpty()) {
            return HttpResult.fail("B0000", I18n.build("租金名称不能为空！"));
        }

        //租金核算方式不能为空
        if (rent.getRentaccounting()==null) {
            return HttpResult.fail("B0000", I18n.build("租金核算方式不能为空！"));
        }
        //租金核算方式为免租时，租金金额默认为0
        if (rent.getRentaccounting() == RentConstant.ACCOUNTING_RENT_FREE) {
            //租金金额为0
            rent.setRentamount("0");
        }
        //租金核算方式不是免租时，租金金额不能为空
        if (rent.getRentaccounting() == RentConstant.ACCOUNTING_FIXED
                || rent.getRentaccounting()==RentConstant.ACCOUNTING_AREA_COUNT) {
            if (rent.getRentamount()==null || rent.getRentamount().isEmpty() || rent.getRentamount().equals("0")) {
                return HttpResult.fail("B0000", I18n.build("租金金额不能为空或0！"));
            }
        }
        //当租金涨幅类型不为空时 判断是阶梯还是什么
        if (rent.getIncreasetype()!=null) {
            //当租金涨幅类型为阶梯租金时，涨幅阶梯大字段不能为空
            if (rent.getIncreasetype()==RentConstant.INCREASE_TYPE_STAIRS) {
                List<Map<String, Object>> ladderList = rent.getLadderList();
                //[{"index":1,"floatType":"1","changeValueOption":"1","changeTime":"23","changeValue":"3232"},{"index":2,"floatType":"1","changeValueOption":"1","changeTime":"232","changeValue":"32323"},{"index":3,"floatType":"1","changeValueOption":"1","changeTime":"3232","changeValue":"3232"}]
                for (int i = 0; i < ladderList.size(); i++) {
                    Map<String, Object> map = ladderList.get(i);
                    //判断涨租时间
                    if (map.get("changeTime").toString()==null || map.get("changeTime").toString().isEmpty()) {
                        //返回阶梯几的浮动类型为空
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租时间不能为空！"));
                    }
                    //校验涨租时间的数据类型
                    if (!RentValidation.containsOnlyDigits(map.get("changeTime").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租时间只能是正整数,且在1-600之间！"));
                    }
                    //判断浮动类型
                    if (map.get("floatType").toString()== null || map.get("floatType").toString().isEmpty()) {
                        //返回阶梯几的浮动类型为空
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的浮动类型不能为空！"));
                    }
                    if (!RentValidation.isFloatType(map.get("floatType").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的浮动类型只能是上浮或下浮！"));
                    }
                    //涨租金额类型
                    if (map.get("changeValueOption").toString()==null || map.get("changeValueOption").toString().isEmpty()) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额类型不能为空！"));
                    }
                    if (!RentValidation.isFloatType(map.get("changeValueOption").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额类型只能是%或金额！"));
                    }
                    //涨租金额
                    if (map.get("changeValue").toString()==null || map.get("changeValue").toString().isEmpty()) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额不能为空！"));
                    }
                    //校验涨租金额
                    if (!RentValidation.isWithinRange(map.get("changeValue").toString())) {
                        return HttpResult.fail("B0000", I18n.build("阶梯"+map.get("index").toString()+"的涨租金额只能输入1-10000000之间的数字！"));
                    }
                }
                //将涨幅阶梯数据转为String类型存入涨幅阶梯中
                String toJSONString = JSONArray.toJSONString(rent.getLadderList());

                rent.setIncreasecontent(toJSONString);

                if (rent.getIncreasecontent()==null || rent.getIncreasecontent().isEmpty()) {
                    return HttpResult.fail("B0000", I18n.build("涨幅阶梯不能为空！"));
                }
            }

            //如果是定额租金，将阶梯置为空
            if (rent.getIncreasetype()==RentConstant.INCREASE_TYPE_QUOTA) {
                rent.setIncreasecontent("");
            }
        }

        ParameterUtil.notNull(rent, "数据不能为空");
        AssertUtil.isTrue(super.updateById(rent), "更新失败");
        return HttpResult.success("更新成功");
    }

    @Override
    public HttpResult<Rent> getById(Long id) {
        ParameterUtil.notNull(id, "缺少数据id");
        Rent data = super.getById(id);
        ParameterUtil.notNull(data, "数据不存在", id);

        if (data.getIncreasetype()==RentConstant.INCREASE_TYPE_STAIRS) {
            //将存在数据库的涨幅阶梯转为数组
            if (data.getIncreasecontent()!=null && !data.getIncreasecontent().isEmpty()) {
                List<Map<String, Object>> maps = JSON.parseObject(data.getIncreasecontent(), new TypeReference<List<Map<String, Object>>>() {
                });
                data.setLadderList(maps);
            }

        }
        return HttpResult.data(data);
    }

    @Override
    public PageResult<FcTreeVo> queryResultVo(PageQuery pageQuery, QueryParams params) {
        PageResult<FcTreeVo> pageResultVo = new PageResult<>();

        SqueryWapper<Rent> squeryWapper = new SqueryWapper<>(Rent.class);
        PageResult<Rent> pageResult = squeryWapper.query(this, pageQuery, params);

        // 对象拷贝
        BeanUtils.copyProperties(pageQuery, pageResultVo);
        // 返回vo
        List<FcTreeVo> listVo = new ArrayList<>();

        pageResult.getList().forEach(item-> {

            FcTreeVo fcTreeVo = new FcTreeVo();

            BeanUtils.copyProperties(item, fcTreeVo);
            fcTreeVo.setParentId("0");
            fcTreeVo.setId(String.valueOf(item.getId()));
            listVo.add(fcTreeVo);
        });

        pageResultVo.setList(listVo);
        pageResultVo.setTotal(Long.valueOf(listVo.size()));

        return pageResultVo;
    }

    @Override
    public Rent getByName(String name) {

        if (StringUtils.isBlank(name)) {
            return new Rent();
        }
        return this.getFirst(Wrappers.<Rent>lambdaQuery().eq(Rent::getName, name));
    }

    @Override
    public Rent getOneById(Long id) {
        if (Objects.isNull(id)) {
            return new Rent();
        }
        return this.getFirst(Wrappers.<Rent>lambdaQuery().eq(Rent::getId, id));
    }

    @Override
    public HttpResult<Serializable> updateSort(List<Map<String, BigInteger>> sortedData) {

        if (null == sortedData || 0 >= sortedData.size()) {
            return HttpResult.fail("4000", "排序数据不可为空", "error");
        }

        sortedData.forEach(item-> {
            if (!item.containsKey("id") || !item.containsKey("orders")) {
                return;
            }
            Long id = item.get("id").longValue(); //类型转换
            int orders = item.get("orders").intValue(); //类型转换
            Rent rent = new Rent();
            rent.setId(id);
            rent.setOrders(orders);
            //执行修改
            super.updateById(rent);
        });
        return HttpResult.success("排序成功");
    }

}
